import {downloadEntering, syncEnteringList} from "../api/input";
import {BugEntering, BugEnterVo, Feed, LocalChange, Room} from "../sql/domin";
import {InputMapper} from "../mappers/InputMapper";
import {LocalChangeMapper} from "../mappers/LocalChangeMapper";
import {mapGetters, useStore} from "vuex";
import {ChangeStatus, ChangeType, TargetType} from "../util/Constants";
import {computed, reactive, ref, toRefs, watch,watchEffect} from "vue";
import {RoomMapper} from "../mappers/RoomMapper";
import {onLoad} from "@dcloudio/uni-app";
import {loginService} from "./login";
import {Guid} from "guid-typescript";
import {parseTime} from "../util/auth";


export function inputService() {

    const store = useStore()

    // 根据服务端数据刷新本地数据
    const refrashEnter = async () => {
        let enters = await downloadEntering()
        let list = enters.data.data as Array<BugEntering>
        await InputMapper.deleteInputByDay(1)
        let localList = await getList()
		localList.forEach(it=>{
			if(it.change == null){
				if(it.enter.id == 0){
					InputMapper.deleteInputByUid(it.enter.uId as string)
				}else{
					InputMapper.deleteInputById(it.enter.id as number)
				}
			}
		})
        for (const it of list) {
            // 如果数据已被修改 则跳过更新
            if (localList.filter(i => i.change != null).length != 0) {
                continue
            }
            // 如果数据已存在但没有更新 则删除原数据插入新数据
            if (localList.filter(i => i.enter.id == it.id).length != 0) {
                InputMapper.insertInput(it)
                continue;
            }
            // 如果数据不存在 则直接插入
            await InputMapper.insertInput(it)
        }
        getList().then((res)=>{
            enterings.value = res
        })
    }

    const syncEnter = async () => {
        let list = await getList() as BugEnterVo[]
        let count = 0;
        syncEnteringList(list.filter(it => it.change != null)).then(res => {
            (res.data.data as BugEnterVo[]).forEach(it => {
                if (it.change?.changeStatus == ChangeStatus.SYNCED) {
                    count += 1
                    LocalChangeMapper.deleteLocalChangeById(it.change.id as number)
                    InputMapper.deleteInputByUid(it.change.targetId as string)
                }
                if (it.change?.changeStatus == ChangeStatus.FAIL) {
                    LocalChangeMapper.updateLocalChangeStatusById(ChangeStatus.FAIL, it.change.id as number)
                }
            })
        })
        return count
    }

    const getList = async () => {
        let list = await InputMapper.selectInputListByDeptId(store.getters.deptId) as Array<BugEntering>
        let res = await LocalChangeMapper.selectLocalChangeList(store.getters.userId, TargetType.INPUT) as Array<LocalChange>
        return list.map(it => {
            return {
                enter: it,
                change: res.filter(i => i.targetId == it.uId)[0]
            } as BugEnterVo
        })
    }

    const enterings = ref<BugEnterVo[]>()


    const handleUpdate = (item:BugEnterVo)=>{
		console.log(item.enter);
        if (item.change == null){
            uni.navigateTo({
                url:'/pages/input/form?id='+item.enter.id
            })
        }else {
            uni.navigateTo({
                url:'/pages/input/form?uId='+item.enter.uId
            })
        }
    }

    const handleDelete = (item:BugEnterVo) => {
        uni.showModal({
            title:'是否撤销修改,该操作将删除记录，请重新刷新',
            success:()=>{
                if (item.change?.changeType == ChangeType.ADD){
                    InputMapper.deleteInputByUid(item.enter.uId as string)
                }else {
                    InputMapper.deleteInputById(item.enter.id as number)
                }
                LocalChangeMapper.deleteLocalChangeById(item.change?.id as number)
            }
        })
    }

    return {
        refrashEnter,
        syncEnter,
        enterings,
        getList,
        handleDelete,
        handleUpdate
    }
}

export function inputFormService() {

    const {getNetWorkType} = loginService()

    onLoad(async (porps) => {
        await getRoomList()
        if (porps.id || porps.uId) {
            type.value = 'upd'
            let list: BugEntering[] = []
            if (porps.id) {
                list = await InputMapper.selectInputById(Number(porps.id)) as BugEntering[]
            }
            if (porps.uId) {
                list = await InputMapper.selectInputByUId(porps.uId) as BugEntering[]
            }
            data.entering = list[0]
            uni.setNavigationBarTitle({
                title: '修改幼虫录入'
            })
        }
    })

    const type = ref()

    const title = computed(()=>{
        return type.value == 'upd' ? '确认修改' : '确认添加'
    })

    const store = useStore()

    const reloadingType = [
        {value: '0', text: '35+28'},
        {value: '1', text: '35+26'},
    ]

    const data = reactive({
            entering: {
                id: 0,
                batchNumber: '',
                bugType: '',
                reloadingStyle: '',
                optionDate: '',
                nextReloadingDate: '',
                sum: 0,
                roomId: undefined,
                digoutMonth: '',
                digoutInfection: '',
                remark: '',
            } as BugEntering
        }
    )

    const getDate = (e:any) => {
        let a = new Date(e)
        let b = a.setDate(a.getDate() + 35);
        // @ts-ignore
        data.entering.nextReloadingDate = parseTime(b, "{y}-{m}-{d}");
    }

    watchEffect(() => data.entering.batchNumber, (newValue, oldValue) => {
        let value = newValue?.replace(/[^\d\-\ \a-zA-Z]/g, "").toUpperCase(); // 只能输入数字.-字母
        value = value?.replace(/ /g, "-");//将空格转换成-
        data.entering.batchNumber = value
    })

    const {entering} = toRefs(data)

    const bindDateChange = (e: any) => {
        entering.value.digoutMonth = e.target.value
    }

    const deptName = computed(
        mapGetters(['deptName']).deptName.bind({$store: store})
    )

    const getRoomList = async () => {
        let a = await RoomMapper.selectRoomList()
        //('99=>',a)
        let list = await RoomMapper.selectRoomListDeptId(store.getters.deptId) as Room[]
        roomList.value = list.map(it => {
            return {
                text: it.roomName,
                value: it.id
            } as roomdata
        })
    }

    type roomdata = {
        text: string,
        value: any
    }

    const roomList = ref<roomdata[]>([])

    const getInfo = (e: any) => {
        if (e.detail.value) {
            let number = e.detail.value
            let a = number.substring(0, 1);      // 截取首字母
            let b = number.split("-");
            let c = b[b.length - 2]
            let digoutYear = '20' + c.substring(0, 2)
            let digoutMouth = c.substring(2, 4)            //截取出土年月
            if (a == "A" || a == "B" || a == "C") {
                if (number.indexOf("YZ") != -1) {
                    entering.value.bugType = "C-YZ";
                } else {
                    entering.value.bugType = "C-QR";
                }
                entering.value.sum = parseInt(b[b.length - 1]) * 50;        // 获取数量
                entering.value.digoutMonth = digoutYear + '-' + digoutMouth     //获取出土月份
            } else if (a == "G" || a == "L") {
                if (number.indexOf("YZ") != -1) {
                    entering.value.bugType = "G-YZ";
                } else {
                    entering.value.bugType = "G-QR";
                }
                entering.value.sum = parseInt(b[b.length - 1]) * 50;         // 获取数量
                entering.value.digoutMonth = digoutYear + '-' + digoutMouth     //获取出土月份
            }
        } else return
    }

    const enter = ref()

    const rules = {
        batchNumber: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写批号',
                }, {
                    validateFunction: function (rule: any, value: any, data: BugEntering, callback: any) {
                        if (value.indexOf(',') == -1){
                            const a = value.substring(0, 1);  //批号首字母
                            const b = value.split("-")
                            if ((a !== "A" && a !== "B" && a !== "C" && a !== "G" && a !== "L") || b.length < 3) {
                                callback("幼虫批号输入错误");
                            } else if (value.indexOf('GL') != -1) {
                                callback("幼虫批号输入错误");
                            }
                            return true
                        }
                        return true
                    }
                }
            ]
        },
        bugType: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写幼虫类型',
                },

            ]
        },
        reloadingStyle: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写换料方式',
                },
            ]
        },
        optionDate: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写挑虫日期',
                },
            ]
        },
        nextReloadingDate: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写下次换料日期',
                },
            ]
        },
        sum: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写数量',
                }
                , {
                    validateFunction: function (rule: any, value: any, data: BugEntering, callback: any) {
                        if (value < 0 || value > 500000) {
                            callback('请输入合理的数量')
                        }
                        return true
                    }
                }
            ]
        },
        roomId: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请选择养虫间',
                },
            ]
        },
        digoutMonth: {
            rules: [
                // 校验 name 不能为空
                {
                    required: true,
                    errorMessage: '请填写出土月份',
                },

            ]
        }
    }

    const handleSubmit = () => {
        enter.value.validate().then(() => {
            if (type.value == undefined) {
                addEnter(entering.value)
            } else {
                updEnter(entering.value)
            }
        })
    }

    const addEnter = (bugEnter: BugEntering) => {
        let guid = Guid.create().toString()
        bugEnter.uId = guid
        bugEnter.createTime = parseTime(new Date()) as string
        bugEnter.deptId = store.getters.deptId
        bugEnter.userId = store.getters.userId
        bugEnter.userName = store.getters.nickname
        bugEnter.roomName = roomList.value.filter(it => it.value == bugEnter.roomId)[0].text
        InputMapper.insertInput(bugEnter).then(() => {
            LocalChangeMapper.insertLocalChange({
                targetId: guid,
                targetType: 'input',
                changeType: 'add',
                userId: store.getters.userId,
                changeStatus: ChangeStatus.UNSYNC,
                changeTime: new Date().toString()
            } as LocalChange).then(() => {
                uni.showToast({
                    title: '幼虫录入成功',
                    icon: 'success',
                    duration: 2000
                })
                uni.navigateBack()
            })
        })
    }

    const updEnter = (bugEnter: BugEntering) => {
        let isUpd = true
        // 判断是否已在本地更新
        if (bugEnter.uId == null) {
            bugEnter.uId = Guid.create().toString()
            isUpd = false
        }
        InputMapper.updateInput(bugEnter).then(() => {
            // 如已在本地更新，则修改 本地更新时间
            if (isUpd) {
                LocalChangeMapper.updateLocalChangeByUid(bugEnter.uId as string, ChangeType.upd, parseTime(new Date(), '{y}-{m}-{d}') as string)
                    .then(() => {
                        uni.showToast({
                            title: '幼虫录入修改成功',
                            icon: 'success',
                            duration: 2000
                        })
                        uni.navigateBack()
                    })
            } else {
                LocalChangeMapper.insertLocalChange({
                    targetId: bugEnter.uId,
                    targetType: TargetType.INPUT,
                    changeType: 'upd',
                    userId: store.getters.userId,
                    changeStatus: ChangeStatus.UNSYNC,
                    changeTime: parseTime(new Date(), '{y}-{m}-{d}') as string
                }).then(() => {
                    uni.showToast({
                        title: '幼虫录入修改成功',
                        icon: 'success',
                        duration: 2000
                    })
                    uni.navigateBack()
                })
            }
        })
    }

    const handleDelete = (item: BugEnterVo) => {

    }

    return {
        entering,
        getInfo,
        reloadingType,
        bindDateChange,
        deptName,
        getRoomList,
        roomList,
        rules,
        enter,
        handleSubmit,
        getDate,
        title
    }

}
